import {ITodoItem} from "../../App.tsx";
import styled from "@emotion/styled";
import {Button, IconButton} from "@mui/material";
import CheckIcon from "@mui/icons-material/Check";
import {ChangeEvent, useRef, useState} from "react";

type IProps = {
    data: ITodoItem;
    onItemComplete: (id: string) => void;
    onEditItem: (title: string) => void;
};

const TodoItemArea = ({
                          data,
                          onItemComplete,
                          onEditItem,
                      }: IProps) => {
    const [editedTitle, setEditedTitle] = useState(data.title);
    const [isEditing, setIsEditing] = useState(false);
    const editInputRef = useRef<HTMLInputElement>(null);

    const handleTitleChange = (e: ChangeEvent<HTMLInputElement>) => {
        setEditedTitle(e.target.value);
    };

    const handleConfirm = (event: { preventDefault: () => void }) => {
        event.preventDefault();
        if (editedTitle.trim() !== data.title) {
            onEditItem(editedTitle.trim());
        }
        setIsEditing(false);
        // 强行失去焦点
        editInputRef.current?.blur();
    };

    return (
        <Main onSubmit={handleConfirm}>
            <EditInput
                ref={editInputRef}
                style={{
                    outline: isEditing ? `2px dashed blue` : `1px solid black`,
                }}
                value={editedTitle}
                onChange={handleTitleChange}
                onFocus={setIsEditing.bind(null, true)}
            />
            {!isEditing && <CompleteButton onClick={() => onItemComplete(data.id)}>
                <CheckIcon style={{
                    opacity: 0,
                }}/>
            </CompleteButton>}
            {
                isEditing && <ConfirmButton variant="contained" onClick={handleConfirm}>确定</ConfirmButton>
            }
        </Main>
    );
};

// const Title = styled.div`
//     outline: 1px solid black;
//     padding: 8px;
//     margin: 8px 0;
//     border-radius: 4px;
//     width: 250px;
// `;

const EditInput = styled.input`
    padding: 12px 0;
    margin: 8px 0;
    border-radius: 4px;
    width: 250px;
    font-size: 16px;
    text-align: center;
    border: none;
`;

const Main = styled.form`
    position: relative;
    display: flex;
    align-items: center;
`;

const CompleteButton = styled(IconButton)`
    position: absolute;
    right: -55px;
    border: black solid 2px;
`;

const ConfirmButton = styled(Button)`
    position: absolute;
    right: -75px;
    border: black solid 2px;
`;

export default TodoItemArea;
